var elasticsearch = require('elasticsearch');

class elastic {
  constructor(host, apiVersion){
    this.client = new elasticsearch.Client({
      host: host || 'localhost:9200',
      sniffOnStart: true,
      sniffInterval: 60000,
      maxSockets:999,
      apiVersion: apiVersion || "5.0"
    });
  };
  
  search (query, callback){
    if (!this.client) return ;
    this.client.search(query).then(function (resp) {
      callback && callback(resp.hits.hits);
    }, function (err) {
    });
  };
  
  scroll(query, callback){
    if (!callback) return false;
    let self = this;
    try{
      query.scroll = '15m';
      query.size = query.size || 1000;
      query.body = { query: query.query || {match_all: { }}, size: query.size };
      delete query.query;
      delete query.size;
      let allSize = 0;
      self.client.search(query, function getMoreUntilDone(error, response) {
        if (error) callback(null);
        else {
          allSize += response.hits.hits.length;
          try{
            callback(response.hits.hits, function (next) {
              if (!next) return;
              if (response.hits.total > allSize) {
                self.client.scroll({scrollId: response._scroll_id, scroll: '15m'}, getMoreUntilDone);
              } else {
                callback(null);
              }
              
            });
          }catch (e){}
        }
      });
      return true;
    }catch (e){
      callback(null);
    }
    return false;
  }
  
  scrollAll(query, callback){
    if (!callback) return false;
    let self = this;
    try{
      query.scroll = '5m';
      query.size = query.size || 1000;
      query.body = { query: query.query || {match_all: { }}, size: query.size };
      delete query.query;
      delete query.size;
      let allSize = 0;
      self.client.search(query, function getMoreUntilDone(error, response) {
        if (error) callback(null);
        else {
          allSize += response.hits.hits.length;
          try{
            callback(response.hits.hits);
          }catch (e){}
          if (response.hits.total > allSize) {
            self.client.scroll({scrollId: response._scroll_id, scroll: '30s'}, getMoreUntilDone);
          } else {
            callback(null);
          }
        }
      });
      return true;
    }catch (e){
      callback(null);
    }
    return false;
  }
  
}

module.exports = elastic;
